package com.emeraldparser.collect;

import com.google.common.base.Objects;

public abstract class OneToManyTransformedSet<F, T> extends AbstractTransformedSet<F, T> {

	protected abstract F unapply(T targetElement);

	protected F unsafeUnapply(Object unsafeTargetElement) throws IllegalArgumentException {
		@SuppressWarnings("unchecked")
		T targetElement = (T) unsafeTargetElement;
		try {
			return unapply(targetElement);
		} catch (ClassCastException e) {
			throw new IllegalArgumentException(e);
		}
	}

	@Override
	public boolean contains(Object o) {
		F sourceElement;
		
		try {
			sourceElement = unsafeUnapply(o);
		} catch (IllegalArgumentException e) {
			return false;
		}
		
		T expectedTargetElement = apply(sourceElement);
		
		return Objects.equal(o, expectedTargetElement);
	}

}
